<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        p {
            height: 1000px;
            border: solid;
            font-size: 3rem;
        }

        #top {
            width: 100px;
            height: 100px;
            background: gray;
            position: fixed;
            right: 30px;
            bottom: 100px;
            color: white;
            justify-content: center;
            align-items: center;
            display: flex;
            font-size: 3rem;
            cursor: pointer;
        }
    </style>

</head>

<body>

    <div id="top" style="display: none;">TOP</div>

    <div id="content">
        <p>p1
            <img src="./imgs/loading.png" data-src="./imgs/1.jpg" width="400px" alt="">
        </p>
        <p>p2
            <img src="./imgs/loading.png" data-src="./imgs/2.jpg" width="400px" alt="">

        </p>
        <p>p3
            <img src="./imgs/loading.png" data-src="./imgs/3.jpg" width="400px" alt="">

        </p>
        <p>p4
            <img src="./imgs/4.jpg" width="400px" alt="">

        </p>
        <p>p5
            <img src="./imgs/loading.png" width="100px" data-src="./imgs/5.jpg" alt="">

        </p>
        <p>p6
            <img src="./imgs/loading.png" width="400px" data-src="./imgs/6.jpg" alt="">
        </p>
    </div>

    <script>
        const imgs = document.querySelectorAll('img[data-src]');

        // 初始化判断
        imgs.forEach(el => {
            // 判断图片是否在可视区域
            const imgPos = el.getBoundingClientRect();
            if (window.innerHeight - imgPos.top > 300 && el.dataset.src !== '') {
                el.src = el.dataset.src;
                el.dataset.src = '';
            }
        })
        // 窗口滚动事件
        window.onscroll = function () {
            imgs.forEach(el => {
                // 判断图片是否在可视区域
                const imgPos = el.getBoundingClientRect();
                if (window.innerHeight - imgPos.top > 300 && el.dataset.src !== '') {
                    el.src = el.dataset.src;
                    el.dataset.src = '';
                }
            })
        }

    </script>

</body>

</html>